/// <reference lib="webworker" />

declare const self: DedicatedWorkerGlobalScope;
import type { IFriendGroupByUser, IFriendGroupWorkData } from "@/types/friend";

interface FriendWorkerMessageEvent extends MessageEvent {
  data: IFriendGroupWorkData;
}

const ctx: Worker = self as any;

ctx.onmessage = function (e: FriendWorkerMessageEvent) {
  const { friendList, friendGroupList } = e.data;
  const groupMap = new Map<number, IFriendGroupByUser>();
  friendGroupList?.forEach((friendGroup) => {
    groupMap.set(friendGroup.id, {
      id: friendGroup.id,
      name: friendGroup.name,
      isDefault: friendGroup?.isDefault || false,
      users: [],
    });
  });
  friendList?.forEach((user) => {
    const group = groupMap.get(user.groupId);
    group?.users.push(user);
  });
  const result = Array.from(groupMap.values());
  ctx.postMessage({ type: "mergeFriendGroup", payload: result });
};
